package com.scpii.api.common.auth.token;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.LinkedHashMap;
import java.util.Map;

import com.scpii.api.common.auth.AuthorizationRequest;
import com.scpii.api.common.auth.ClientAuthentication;

public class DefaultAuthenticationKeyGenerator implements
		AuthenticationKeyGenerator {

	private static final String CLIENT_ID = "clientId";

	private static final String USERNAME = "username";

	public String extractKey(ClientAuthentication authentication) {
		Map<String, String> values = new LinkedHashMap<String, String>();
		AuthorizationRequest authorizationRequest = authentication
				.getAuthorizationRequest();
		if (!authentication.isClientOnly()) {
			values.put(USERNAME, authentication.getName());
		}
		values.put(CLIENT_ID, authorizationRequest.getAppId());
		MessageDigest digest;
		try {
			digest = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			throw new IllegalStateException(
					"MD5 algorithm not available.  Fatal (should be in the JDK).");
		}
		try {
			byte[] bytes = digest.digest(values.toString().getBytes("UTF-8"));
			return String.format("%032x", new BigInteger(1, bytes));
		} catch (UnsupportedEncodingException e) {
			throw new IllegalStateException(
					"UTF-8 encoding not available.  Fatal (should be in the JDK).");
		}
	}

}
